package com.dingwen.treasure.file.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.dingwen.treasure.easyexcel.ExcelEntity;
import com.google.common.net.HttpHeaders;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * 　ExcelService
 * 　@author dingwen
 * 　@date 2022/8/2
 */
@Component
public class ExcelService {

    /**
     * 下载(TODO 此处通过模版渲染，待优化)
     *
     * @param response    响应
     * @param excelEntity excel实体
     */
    @SneakyThrows(Exception.class)
    public void download(HttpServletResponse response, ExcelEntity excelEntity) {
        // 响应设置
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");

        // 基础模版文件路径
        InputStream resourceAsStream = this.getClass().getClassLoader()
                .getResourceAsStream("EasyExcel.xlsx");

        String fileName = URLEncoder.encode("test", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 这里 会填充到第一个sheet， 然后文件流会自动关闭
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(resourceAsStream).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();

        excelWriter.fill(excelEntity.getEntity(), writeSheet);

        //开启自动换行,自动换行表示每次写入一条list数据是都会重新生成一行空行,此选项默认是关闭的,需要提前设置为true
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(excelEntity.getExcelEntities(), fillConfig, writeSheet);
        excelWriter.finish();
    }
}
